﻿using ConfExpert.Forms.Base;
using DevExpress.XtraEditors;
using DevExpress.XtraEditors.Repository;
using DevExpress.XtraGrid.Columns;
using DevTeam;
using System;
using System.Data;
using System.Windows.Forms;

namespace ConfExpert.Forms.Depo
{
    public partial class HLUretimListe : XForm
    {
        public HLUretimListe()
        {
            InitializeComponent();
        }

        BindingSource bs;
        private void HLUretimListe_Load(object sender, EventArgs e)
        {
            this.Text = "HL Uretim Listesi";

            gleCustomer.Edit.Assign(RI(Rp.V_Customer));
            //RepositoryItemGridLookUpEdit riCustomers = GetCustomGLE(dt, "Name", "CustomerId");
            //gleOwner.Properties.Assign(riCustomers);
            bs = gridView1.Init("GetHL2Uretim_Liste", gleCustomer.EditValue.ToInt());
            gridView1.AddDetailGrid(gridView2, "ProductId, CustomerId");
            gridView1.AddDetailGrid(gridView3, "ProductId, CustomerId");
            gridView1.AddDetailGrid(gridView4, "ProductId, CustomerId");
            /*DevExpress.XtraGrid.Columns.GridColumn col = gridView1.Columns["UretiminHLyeOrani"];
            col.DisplayFormat.FormatType = DevExpress.Utils.FormatType.Numeric;
            col.DisplayFormat.FormatString = "P1";

            // gridView1.Columns["UretiminHLyeOrani"].VisibleIndex = 1;
            gridView1.Columns["UretiminHLyeOrani"].ToolTip = "Üretimin HL'ye Oranı";
            ///gridView1.FormatAsPercentage("UretiminHLyeOrani");
            gridView1.SetCaptions("UretiminHLyeOrani:Üretim/HL");*/
            gridView1.AddColumn("HL", typeof(int), "COUNT(Child({FK}).POLinesId)", 0);
            gridView1.AddColumn("Kalan", typeof(int), "SUM(Child({FK}).Drm)", 0);
            gridView1.AddColumn("Numune", typeof(int), "COUNT(Child({FK}).POLinesId)", 1);
            gridView1.AddColumn("Uretim", typeof(int), "COUNT(Child({FK}).POLinesId)", 2);
            bs.Filter = "Uretim>0 OR Numune>0";

            //gridView1.FormatAsNumber(1, "HL", "Numune","Uretim");
            gridView1.MakeRowSelectable();
            gridView1.MakeColumnsReadOnly("CustomerId", "ProductId", "HL", "Kalan", "Numune",  "Uretim");
            gridView1.MakeColumnInvisible("CustomerId");

            gridView1.SetToolTip("Kalan:İşaretlenmemiş Handloom Sayısı");

            GridManager gm;
            gm = GridManager.GetManager(gridView1);
            gm.GridMenu.AddMenu("Çöz", Coz);

            gridView1.FormatAsNumber(0, "HL", "Numune", "Uretim");
            gridView3.FormatAsNumber(1, "NumuneQty");
            gridView4.FormatAsNumber(1, "UretimQty");

            gridView1.AddSummary("HL", "Numune", "Uretim");
            gridView2.MakeColumnInvisible("CustomerId");
            gridView3.MakeColumnInvisible("CustomerId");
            gridView4.MakeColumnInvisible("CustomerId");
            gridView2.MakeColumnInvisible("Drm");
            gridView1.YanYanaGetirSoluna("Tarih", "POLinesId");
            gridView2.YanYanaGetirSoluna("Tarih", "POLinesId");
            gridView3.YanYanaGetirSoluna("Tarih", "POLinesId");
            gridView4.YanYanaGetirSoluna("Tarih", "POLinesId");
            gridView3.YanYanaGetirSagina("Sec", "Durum");
            gridView4.YanYanaGetirSagina("Sec", "Durum");
            gridView2.MakeColumnsReadOnly("Tarih", "PONr", "POLinesId", "Durum");
            gridView3.MakeColumnsReadOnly("Tarih", "PONr", "POLinesId", "Durum", "NumuneQty");
            gridView4.MakeColumnsReadOnly("Tarih", "PONr", "POLinesId", "Durum", "UretimQty");
            gridView2.SetViewCaption("Handloom");
            gridView3.SetViewCaption("Numune");
            gridView4.SetViewCaption("Sipariş");
            gridView1.BestFitColumns();
            gridView2.BestFitColumns();
            gridView3.BestFitColumns();
            gridView4.BestFitColumns();

            //gleCustomer.EditValueChanged += gleCustomer_EditValueChanged;
            ((RepositoryItemGridLookUpEdit)gleCustomer.Edit).Closed += HLUretimListe_Closed;
            gridView1.FocusedRowChanged += gridView1_FocusedRowChanged;
            gridView2.RowCellClick += gridView2_RowCellClick;
            gridView3.RowCellClick += gridView3_RowCellClick;
            gridView4.RowCellClick += gridView4_RowCellClick;
            this.Shown += HLUretimListe_Shown;
            chkTumunuGoster.CheckedChanged += chkTumunuGoster_CheckedChanged;
            btnBagla.ItemClick += btnBagla_Click;
        }

        void chkTumunuGoster_CheckedChanged(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            bs.Filter = (chkTumunuGoster.Checked ? "" : "Uretim>0 OR Numune>0");
        }

        void HLUretimListe_Shown(object sender, EventArgs e)
        {
            splitContainerControl2.AutoSize();
            splitContainerControl3.AutoSize();
        }

        void HLUretimListe_Closed(object sender, DevExpress.XtraEditors.Controls.ClosedEventArgs e)
        {
            gridView1.RefreshDataSource(true, "GetHL2Uretim_Liste", gleCustomer.EditValue.ToInt());
            //gridView1.Init("GetHL2Uretim_Liste", gleCustomer.EditValue.ToInt());
            //gridView1.AddDetailGrid(gridView2, "ProductId");
            //gridView1.AddDetailGrid(gridView3, "ProductId");
            //gridView1.AddDetailGrid(gridView4, "ProductId");
            //gridView1.AddColumn("HL", typeof(int), "COUNT(Child({FK}).POLinesId)", 0);
            //gridView1.AddColumn("Numune", typeof(int), "COUNT(Child({FK}).POLinesId)", 1);
            //gridView1.AddColumn("Uretim", typeof(int), "COUNT(Child({FK}).POLinesId)", 2);
            ////gridView1.FormatAsNumber(1, "HL", "Numune", "Uretim");
            //gridView1.MakeRowSelectable();
            //gridView1.MakeColumnsReadOnly("CustomerId", "ProductId", "HL", "Numune", "Uretim");
            //gridView1.MakeColumnInvisible("CustomerId");
            //gridView1.AddSummary("HL", "Numune", "Uretim");
            //gridView2.MakeColumnInvisible("CustomerId");
            //gridView3.MakeColumnInvisible("CustomerId");
            //gridView4.MakeColumnInvisible("CustomerId");
            gridView1.BestFitColumns();
            gridView2.BestFitColumns();
            gridView3.BestFitColumns();
            gridView4.BestFitColumns();
        }

        void gridView1_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            if (e.PrevFocusedRowHandle < 0) return;
            DataRow dr = gridView1.GetDataRow(e.PrevFocusedRowHandle);
            if (dr != null)
            {
                if (!BaglanmalarDogruMu(gridView2.DataTable(), gridView3.DataTable(), gridView4.DataTable(), dr["ProductId"].ToInt(), gleCustomer.EditValue.ToInt()))
                {
                    XtraMessageBox.Show("Üretim Kaydı Seçmediğiniz Takdirde HL'den ve Numune'den Sadece 1 Seçim Yapabilirsiniz!", "Uyarı");
                    gridView1.FocusedRowHandle = e.PrevFocusedRowHandle;
                }
            }
        }

        void gridView4_RowCellClick(object sender, DevExpress.XtraGrid.Views.Grid.RowCellClickEventArgs e)
        {
            if (e.Column.FieldName == "Sec")
            {
                if (gridView4.GetDataRow(e.RowHandle) != null && gridView4.GetDataRow(e.RowHandle)["Durum"].ToStr().Equals("BAĞLANDI"))
                {
                    XtraMessageBox.Show("Bağlı Kayıtlar İçinden Seçim Yapamazsınız!", "Uyarı");
                    GridColumn gc = gridView4.Columns["Durum"];
                    gridView4.FocusedColumn = gc;
                    return;
                }
                bool currentStatus = false;
                if (e.CellValue != DBNull.Value)
                {
                    currentStatus = e.CellValue.ToBool();
                }
                gridView4.SetRowCellValue(e.RowHandle, e.Column, !currentStatus);
            }
        }

        void gridView3_RowCellClick(object sender, DevExpress.XtraGrid.Views.Grid.RowCellClickEventArgs e)
        {
            if (e.Column.FieldName == "Sec")
            {
                if (gridView3.GetDataRow(e.RowHandle) != null && gridView3.GetDataRow(e.RowHandle)["Durum"].ToStr().Equals("BAĞLANDI"))
                {
                    XtraMessageBox.Show("Bağlı Kayıtlar İçinden Seçim Yapamazsınız!", "Uyarı");
                    GridColumn gc = gridView3.Columns["Durum"];
                    gridView3.FocusedColumn = gc;
                    return;
                }
                bool currentStatus = false;
                if (e.CellValue != DBNull.Value)
                {
                    currentStatus = e.CellValue.ToBool();
                }
                gridView3.SetRowCellValue(e.RowHandle, e.Column, !currentStatus);
            }
        }

        void gridView2_RowCellClick(object sender, DevExpress.XtraGrid.Views.Grid.RowCellClickEventArgs e)
        {
            if (e.Column.FieldName == "Sec")
            {
                if (gridView2.GetDataRow(e.RowHandle) != null && gridView2.GetDataRow(e.RowHandle)["Durum"].ToStr().Equals("BAĞLANDI"))
                {
                    XtraMessageBox.Show("Bağlı Kayıtlar İçinden Seçim Yapamazsınız!", "Uyarı");
                    GridColumn gc = gridView2.Columns["Durum"];
                    gridView2.FocusedColumn = gc;
                    return;
                }
                bool currentStatus = false;
                if (e.CellValue != DBNull.Value)
                {
                    currentStatus = e.CellValue.ToBool();
                }
                gridView2.SetRowCellValue(e.RowHandle, e.Column, !currentStatus);
            }
        }

        /*void gleCustomer_EditValueChanged(object sender, EventArgs e)
        {
            gridView1.Init("GetHL2Uretim_Liste", gleCustomer.EditValue.ToInt());
            gridView1.AddDetailGrid(gridView2, "ProductId");
            gridView1.AddDetailGrid(gridView3, "ProductId");
            gridView1.AddDetailGrid(gridView4, "ProductId");
            gridView1.AddColumn("HL", typeof(int), "COUNT(Child({FK}).PONr)", 0);
            gridView1.AddColumn("Numune", typeof(int), "COUNT(Child({FK}).PONr)", 1);
            gridView1.AddColumn("Uretim", typeof(int), "COUNT(Child({FK}).PONr)", 2);
            //gridView1.FormatAsNumber(1, "HL", "Numune", "Uretim");
            gridView1.MakeRowSelectable();
            gridView1.MakeColumnsReadOnly("CustomerId", "ProductId", "HL", "Numune", "Uretim");
            gridView1.MakeColumnInvisible("CustomerId");
            gridView1.AddSummary("HL", "Numune", "Uretim");
            gridView1.BestFitColumns();
            gridView2.BestFitColumns();
            gridView3.BestFitColumns();
            gridView4.BestFitColumns();
        }*/

        private void btnBagla_Click(object sender, EventArgs e)
        {
            DataRow dr = gridView1.GetFocusedDataRow();
            if (dr != null)
            {
                if (!BaglanmalarDogruMu(gridView2.DataTable(), gridView3.DataTable(), gridView4.DataTable(), dr["ProductId"].ToInt(), gleCustomer.EditValue.ToInt()))
                {
                    XtraMessageBox.Show("Üretim Kaydı Seçmediğiniz Takdirde HL'den ve Numune'den Sadece 1 Seçim Yapabilirsiniz!", "Uyarı");
                    return;
                }
            }
            String BaglanmaListesi = GetBaglanmaList();
            if (BaglanmaListesi.Equals(String.Empty))
                XtraMessageBox.Show("Bağlanacak Öğeleri Seçmediniz!", "Uyarı");
            else
            {
                ExecuteNonQuery("InsHLBaglanma", BaglanmaListesi, gleCustomer.EditValue.ToInt());
                int Frh = gridView1.FocusedRowHandle;
                gridView1.RefreshDataSource("GetHL2Uretim_Liste", gleCustomer.EditValue.ToInt());
                
                gridView1.ClearSelection();
                gridView1.SelectRow(Frh);
                gridView1.FocusedRowHandle = Frh;
                gridView2.OptionsBehavior.EditorShowMode = 
                gridView3.OptionsBehavior.EditorShowMode = 
                gridView4.OptionsBehavior.EditorShowMode = DevExpress.Utils.EditorShowMode.MouseUp;
            }

            
        }

        private bool BaglanmalarDogruMu(DataTable dtHL, DataTable dtNumune, DataTable dtUretim, int ProductId, int CustomerId)
        {
            bool retVal = false;
            bool dtUretimdeCheckVar = false;
            int dtHLNumberOfChecks = 0,
                dtNumuneNumberOfChecks = 0;
            for (int i = 0; i < dtHL.Rows.Count; ++i)
            {
                if (dtHL.Rows[i]["ProductId"].ToInt() == ProductId && dtHL.Rows[i]["CustomerId"].ToInt() == CustomerId)
                {
                    if (dtHL.Rows[i]["Sec"].ToBool() == true)
                        ++dtHLNumberOfChecks;
                }
            }

            for (int i = 0; i < dtNumune.Rows.Count; ++i)
            {
                if (dtNumune.Rows[i]["ProductId"].ToInt() == ProductId && dtNumune.Rows[i]["CustomerId"].ToInt() == CustomerId)
                {
                    if (dtNumune.Rows[i]["Sec"].ToBool() == true)
                        ++dtNumuneNumberOfChecks;
                }
            }

            for (int i = 0; i < dtUretim.Rows.Count; ++i)
            {
                if (dtUretim.Rows[i]["ProductId"].ToInt() == ProductId && dtUretim.Rows[i]["CustomerId"].ToInt() == CustomerId)
                {
                    if (dtUretim.Rows[i]["Sec"].ToBool() == true)
                    {
                        dtUretimdeCheckVar = true;
                        break;
                    }
                }
            }

            if ((dtHLNumberOfChecks == 1 && dtNumuneNumberOfChecks == 1) || (dtHLNumberOfChecks == 1 && dtNumuneNumberOfChecks == 0 && dtUretimdeCheckVar)
                   || (dtHLNumberOfChecks == 0 && dtNumuneNumberOfChecks == 1 && dtUretimdeCheckVar)
                   || (dtHLNumberOfChecks == 0 && dtNumuneNumberOfChecks == 0 && dtUretimdeCheckVar == false))
                retVal = true;

            return retVal;
        }

        private String GetBaglanmaList()
        {
            string retStr = "";
            bool HLeUgradi = false,
                 NumuneyeUgradi = false;
            DataTable dtProductList = gridView1.DataTable();
            DataTable dtHL = gridView2.DataTable();
            DataTable dtNumune = gridView3.DataTable();
            DataTable dtUretim = gridView4.DataTable();

            for (int i = 0; i < dtProductList.Rows.Count; ++i)
            {
                HLeUgradi = false;
                NumuneyeUgradi = false;

                for (int j = 0; j < dtHL.Rows.Count; ++j)
                {
                    if (dtHL.Rows[j]["ProductId"].ToInt() == dtProductList.Rows[i]["ProductId"].ToInt() && dtHL.Rows[j]["CustomerId"].ToInt() == gleCustomer.EditValue.ToInt() && dtHL.Rows[j]["Sec"].ToBool() == true)
                    {

                        retStr += dtHL.Rows[j]["ProductId"].ToStr() + "," + dtHL.Rows[j]["POLinesId"].ToStr() + ",";
                        HLeUgradi = true;
                        break;
                    }
                }
                for (int k = 0; k < dtNumune.Rows.Count; ++k)
                {
                    if (dtNumune.Rows[k]["ProductId"].ToInt() == dtProductList.Rows[i]["ProductId"].ToInt() && dtNumune.Rows[k]["CustomerId"].ToInt() == gleCustomer.EditValue.ToInt() && dtNumune.Rows[k]["Sec"].ToBool() == true)
                    {
                        if (HLeUgradi)
                            retStr += dtNumune.Rows[k]["POLinesId"].ToStr();
                        else
                            retStr += dtNumune.Rows[k]["ProductId"].ToStr() + ",," + dtNumune.Rows[k]["POLinesId"].ToStr();
                        NumuneyeUgradi = true;
                        break;
                    }
                }
                for (int l = 0; l < dtUretim.Rows.Count; ++l)
                {
                    if (dtUretim.Rows[l]["ProductId"].ToInt() == dtProductList.Rows[i]["ProductId"].ToInt() && dtUretim.Rows[l]["CustomerId"].ToInt() == gleCustomer.EditValue.ToInt() && dtUretim.Rows[l]["Sec"].ToBool() == true)
                    {
                       /* if (HLeUgradi && NumuneyeUgradi && UretimeUgradi == false)
                            retStr += "," + dtUretim.Rows[l]["PONr"].ToStr();
                        else if (HLeUgradi && NumuneyeUgradi && UretimeUgradi == true)
                            retStr += "," + dtUretim.Rows[l]["PONr"].ToStr();
                        else if (HLeUgradi && !NumuneyeUgradi && UretimeUgradi == false)
                            retStr += ",," + dtUretim.Rows[l]["PONr"].ToStr();
                        else if (HLeUgradi && !NumuneyeUgradi && UretimeUgradi == true)
                            retStr += "," + dtUretim.Rows[l]["PONr"].ToStr();
                        else if (!HLeUgradi && NumuneyeUgradi && UretimeUgradi == false)
                            retStr += "," + dtUretim.Rows[l]["PONr"].ToStr();
                        else if (!HLeUgradi && NumuneyeUgradi && UretimeUgradi == true)
                            retStr += "," + dtUretim.Rows[l]["PONr"].ToStr();*/
                        //else if (!HLeUgradi && !NumuneyeUgradi && UretimeUgradi == false) HL'ye ya da Numuneye, En az birine Ugramak Zorunda!
                        
                        // Yukardaki uzun mantigin aynisini bu yapıyor
                        //if (HLeUgradi && !NumuneyeUgradi && UretimeUgradi == false)
                        //    retStr += ",," + dtUretim.Rows[l]["PONr"].ToStr();
                        //else
                        retStr += "," + dtUretim.Rows[l]["POLinesId"].ToStr();                        
                    }
                }

                if (HLeUgradi || NumuneyeUgradi)
                {
                    retStr += "|";
                }
            }

            if (retStr.Equals(String.Empty))
                return String.Empty;
            else
                return retStr.Substring(0, retStr.Length-1);
        }

        void Coz(object sender, EventArgs e)
        {
            int Frh = gridView1.FocusedRowHandle;
            ExecuteNonQuery("DelHLBaglanma", gridView1.GetFocusedDataRow()["ProductId"].ToInt(), gleCustomer.EditValue.ToInt());
            gridView1.RefreshDataSource("GetHL2Uretim_Liste", gleCustomer.EditValue.ToInt());
            gridView1.ClearSelection();
            gridView1.SelectRow(Frh);
            gridView1.FocusedRowHandle = Frh;
            gridView2.OptionsBehavior.EditorShowMode = 
            gridView3.OptionsBehavior.EditorShowMode = 
            gridView4.OptionsBehavior.EditorShowMode = DevExpress.Utils.EditorShowMode.MouseUp;
        }
    }
}
